<?php

//首页管理
class SiteController extends Controller
{
	//今日主推
	public function actionRecommend()
	{
		$recommendModel = new Recommend;
		if (isset($_POST['Recommend']) && !empty($_POST['Recommend']['book_id']))
		{
			if($recommendModel->findByPk($_POST['Recommend']['book_id']) === NULL)
			{
				$sql = 'INSERT INTO '.$recommendModel->tableName().' SELECT * FROM {{book}} WHERE book_id = '.$_POST['Recommend']['book_id'];
				if(Yii::app()->db->createCommand($sql)->execute() == 0)
				{
					$this->error('添加失败！');
				}
			}else{
				$this->error('该小说已存在！');
			}
			
		}
		$this->render('recommend', array('model'=>$recommendModel));
	}

	//随机推荐
	public function actionRand()
	{
		$randModel = new Rand;
		if (isset($_POST['Rand']) && !empty($_POST['Rand']['book_id']))
		{
			if($randModel->findByPk($_POST['Rand']['book_id']) === NULL)
			{
				$sql = 'INSERT INTO '.$randModel->tableName().' SELECT * FROM {{book}} WHERE book_id = '.$_POST['Rand']['book_id'];
				if(Yii::app()->db->createCommand($sql)->execute() == 0)
				{
					$this->error('添加失败！');
				}
			}else{
				$this->error('该小说已存在！');
			}
				
		}
		$this->render('rand', array('model'=>$randModel));
	}
	
	//程序自动随机添加
	public function actionAutoRand()
	{
		Rand::model()->deleteAll();
		$sql = 'INSERT INTO {{rand}} SELECT * FROM {{book}} ORDER BY rand() LIMIT 6';
		Yii::app()->db->createCommand($sql)->execute();
		echo '1';
		Yii::app()->end();
	}
	
	//修改
	public function actionEdit()
	{
		$type 	= ucfirst($_GET['type']);
		$model	= $type::model()->findByPk($_GET['book_id']);
		if (isset($_POST[$type]))
		{
			$model->attributes = $_POST[$type];
			if ($model->save())
			{
				$this->success();
			}else{
				$this->error($model->getErrors());
			}
		}
		$model->book_finish_time = date('Y-m-d',$model->book_finish_time);
		$this->render('edit', array('model'=>$model));
	}
	
	//删除
	public function actionDelete()
	{
		$type	= ucfirst($_GET['type']);
		$type::model()->deleteByPk($_GET['book_id']);
		$this->redirect(Yii::app()->request->urlReferrer);
	}
	
	public function actionGetBookTitle()
	{
		$model = Book::model()->findByPk($_POST['book_id']);
		if( ! empty($model))
		{
			echo $model->book_title;
		}
		Yii::app()->end();
	}
	
	
}